/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Apr 14, 2012
 * Time: 4:14:41 PM
 * To change this template use File | Settings | File Templates.
 */
/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Mar 31, 2012
 * Time: 8:29:44 PM
 * To change this template use File | Settings | File Templates.
 */
/***************************/

  //global vars
	var form = $("#frmData");
	var lotId = $("#lotId");
	var cardIdInfo = $("#cardIdInfo");
	var cardId = $("#cardId");

    var isEdit = false;

$(document).ready(function(){


	form.submit(function(){
		if(validateCardId())
			return true
		else
			return false;
	});

    cardId.blur(validateCardId);

    //disableForm("frmData");
} );

	function validateCardIdlLength(){
		//if it's NOT valid
		if(cardId.val().length < 4){
			cardId.addClass("errorField");
			cardIdInfo.text("please enter morethan 4 digit number!");
			cardIdInfo.addClass("errorField");
			return false;
		}
		//if it's valid
		else{
			cardId.removeClass("errorField");
			cardIdInfo.text("");
			cardIdInfo.removeClass("errorField");
			return true;
		}
	}

  function clearValidate(){
        cardId.removeClass("errorField");
        cardIdInfo.text("");
        cardIdInfo.removeClass("errorField");
  }
function validateCardId(fn){

        if (validateCardIdlLength()) {
            //test with db
            var params =encodeURIComponent("cardId") + "="+cardId.val();
            ajaxPost("?tld/checkCard", params, function(data) {
			var response =JSON.parse(data);
			if (response.status==false) {
				return;
			}
             if(response.message){
                cardId.removeClass("errorField");
		        cardIdInfo.text("");
			    cardIdInfo.removeClass("errorField");
                if (typeof fn === 'function') {
                    fn();
                }
			    return true;
             }else{
                cardId.addClass("errorField");
			    cardIdInfo.text("Card ID alredy exist !");
			    cardIdInfo.addClass("errorField");
			    return false;
             }
		});

        }
}

//////page data  ////
var isNew = false;

//////////// data Grid /////////
var mygrid;
var timeoutHnd;
var flAuto = false;
function gridGenerator() {
    mygrid = new dhtmlXGridObject('gridbox');
    mygrid.setImagePath("images/dhtmlx/imgs/");
    mygrid.setHeader("Id,Lot Name,Code,Pass performance Test,Deosemiter,QA card");
    mygrid.setInitWidths("50,350,150,200,100,100");
    mygrid.setColAlign("center,left,center,center,center,center");
    mygrid.setColSorting("server,server,server,na,na,na");
    mygrid.setColTypes("ro,ro,ro,ch,ch,ch");
    mygrid.getCombo(5).put(2, 2);
    if (mygrid.setColspan){
       mygrid.attachEvent("onBeforeSorting", customColumnSort);
    }

    //mygrid.enablePaging(mode,pageSize,pagesInGrp,pagingControlsContainer,showRecInfo,pagingStateContainer);
    mygrid.enablePaging(true,10, 10, "pagingArea", true, "infoArea");
   // mygrid.setPagingSkin("bricks");
    mygrid.setPagingSkin("toolbar", "dhx_skyblue");
    //mygrid.setStyle("background-color:navy;color:white; font-weight:bold;", "","color:red;", "");
    mygrid.init();
    mygrid.setSkin("dhx_skyblue"); //other skins (sbdark,gray,mt,xp,clear,modern,light,dhx_skyblue )
    mygrid.attachEvent("onBeforePageChanged", function() {
        if (!this.getRowsNum()){
            return false;
        }
        return true;
    });
    mygrid.sortField_old = mygrid.sortField;
    mygrid.sortField = function() {
        mygrid.setColSorting("str,str,str,str,str,str");
        if (customColumnSort(arguments[0]))
        mygrid.sortField_old.apply(this, arguments);
    }
   // mygrid.setColumnHidden(3,true);
    mygrid.sortRows = function(col, type, order) {}
    mygrid.attachEvent("onRowSelect",doOnRowSelected);
    mygrid.attachEvent("onXLE", showLoading);
    mygrid.attachEvent("onXLS", function() {
        showLoading(true)
    });
    mygrid.loadXML("?tld/gridTld&un=" + Date.parse(new Date()),function(){
      var myToolbar=mygrid.aToolBar;
        //myToolbar.setSkin("dhx_black");

   });
}

function showLoading(fl) {
    var span = document.getElementById("recfound");
    if (!span)
        return;
    if (!mygrid._serialise) {
        span.innerHTML = "<i>Loading... available in Professional Edition of dhtmlxGrid</i>";
        return;
    }
    span.style.color = "red";
    if (fl === true)
    span.innerHTML = "loading...";
    else
    span.innerHTML = "";
}

function doSearch(ev) {
    if (!flAuto)
    return;
    var elem = ev.target || ev.srcElement;
    if (timeoutHnd)
    clearTimeout(timeoutHnd);
    timeoutHnd = setTimeout(reloadGrid, 500);
}
function reloadGrid() {
    var searchCriteriaLotName = document.getElementById("searchCriteria.lotName").value;
    var searchCriteriaCode = document.getElementById("searchCriteria.code").value;
    showLoading(true);
    mygrid.clearAndLoad("?tld/gridTld&lotId=" + searchCriteriaLotName + "&code=" + searchCriteriaCode +"&orderBy=" +   window.s_col + "&direction=" + window.a_direction);
    if (window.a_direction)
    mygrid.setSortImgState(true, window.s_col, window.a_direction);
}
function enableAutosubmit(state) {
    flAuto = state;
    document.getElementById("submitButton").disabled = state;
}

function customColumnSort(ind) {
    if (ind == 3) {
        alert("Table can't be sorted by this column.");
        if (window.s_col)
        mygrid.setSortImgState(true, window.s_col, window.a_direction);
        return false;
    }
    var a_state = mygrid.getSortingState();
    window.s_col = ind;
    window.a_direction = ((a_state[1] == "des") ? "asc": "des");
   reloadGrid();
    return true;
}

function doOnRowSelected(rowID,celInd){

}



function initialize(fnAfterInit) {
    clearForm("frmData");
    clearValidate();
   // disableForm("frmData");   
   // handleDefaultButtons("edit");

}

function save(){
    validateCardId(
                function(){
                      document.getElementById("id").value  = lotId.val();
                        var params = serializeForm("frmData") ;
                        ajaxPost("?tld/addTldCard", params, function(data) {

			            var response =JSON.parse(data);

			            if (response.status==false) {
				        return;
			            }

                        // Success
                        //actionResponse = response;
                        $("#messagePanel").removeClass();
                        $("#messagePanel").addClass(response.type);
                        $("#messagePanel").html(response.message ) ;
                      //  reloadGrid();
			            initialize();

                       return;

		                });
                    }
            )

  //  handleDefaultButtons("save");
}


function closePage(){
    window.location.href="?home";
}

function onLoad(){
     initialize();
     gridGenerator();
     enforcePrivileges();
     handleDefaultButtons("edit");
}

onLoad();